package org.itboys.shop.controller;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.itboys.commons.CommonConstants;
import org.itboys.commons.CommonConstants.NUM;
import org.itboys.commons.CommonConstants.StaticParam;
import org.itboys.commons.utils.ajax.AjaxUtils;
import org.itboys.commons.utils.number.C;
import org.itboys.commons.utils.tools.ImagePathUtils;
import org.itboys.commons.utils.tools.ResponseManager;
import org.itboys.framework.spring.controller.BaseController;
import org.itboys.member.entity.Member;
import org.itboys.product.entity.Product;
import org.itboys.product.entity.ProductSpecDetail;
import org.itboys.product.service.ProductService;
import org.itboys.product.service.ProductSpecDetailService;
import org.itboys.shop.service.Manager.WXProManager;
import org.itboys.shop.tools.WXSession;
import org.itboys.trade.dto.CartItemDto;
import org.itboys.trade.entity.Cart;
import org.itboys.trade.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.google.common.collect.Maps;

/**
 * 商品
 * @author 
 *
 */
@RestController
@RequestMapping("/wx/cart")
public class WXCartController extends BaseController{
	@Autowired
	private CartService cartService;
	@Autowired
	private ProductService productService;
	@Autowired
	private WXProManager proManager;
	@Autowired
	private ProductSpecDetailService specDetailService;
	/**
	 * 跳转到购物车页面
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/cartIndex")
	public ModelAndView toListVM(Model model,HttpServletRequest request, HttpServletResponse response) {
//		boolean isLogin = false ;
//		String userId;//如果登录状态
		List<Cart> carts;
//		if(isLogin){
//			userId = SessionHolder.getMemberId();
			Long memberId = WXSession.getMember(request).getId();
			carts = cartService.getCartListByMemberId(memberId);
			
//		}else{
//			userId = CookieUtils.getValueFromCookie(request, "cookieId");
//			carts = cartService.getCartListByCookiesId(userId);
//		}
		
		//productService.getById(id);
		List<CartItemDto>results=carts.stream().map(c->{
			CartItemDto dto=new CartItemDto();
			Product pro=productService.getById(c.getProductId());
			if (null==pro) {
				cartService.delete(c.getId());
			}else {
				dto.setCartId(c.getId());
				dto.setElement(c.getElements());
//				dto.setFee((Double)C.multiply(C.divid(c.getPrice(),100d),c.getNum()));
				dto.setNum(c.getNum());
				dto.setProImage(ImagePathUtils.add(StaticParam.imagePath, pro.getImage()));
				dto.setProName(pro.getName());
				dto.setProPrice(NUM.DF_00.format(c.getPrice()/100d));
				ProductSpecDetail detail=specDetailService.getById(c.getSpecDetailId());
				if (null!=detail) {
					dto.setNumLimit(detail.getStock());
				}else{
					dto.setNumLimit(0l);
				}
				
				return dto;
			}
			return null;
		}).collect(Collectors.toList());
		model.addAttribute("carts", results);
		return new ModelAndView("/cart/Cart");
	}
	/**
	 * 添加商品到购物车
	 * @param request
	 * @param cart
	 * @param response
	 */
	@ResponseBody
	@RequestMapping("/addCart")
	public void addCart(
			@RequestParam Long proId,
			@RequestParam Long specId,
			@RequestParam Integer num,
			HttpServletRequest request
			,HttpServletResponse response){
		try{
			Member member=WXSession.getMember(request);
//			if (null==member) {
//				AjaxUtils.renderText(response, CommonConstants.FAIL);
//				return;
//			}
			Cart cart=new Cart();
			ProductSpecDetail spec=specDetailService.getById(specId);
			cart.setElements(proManager.getSpecName(spec.getCategorySpecDetailIds()).replace("/", " "));
			cart.setPrice((Integer)C.multiply(100,spec.getPrice()));
			cart.setFee((Integer)C.multiply(num,cart.getPrice()));
			cart.setMemberId(member.getId());
			cart.setNum(num);
			cart.setProductId(proId);
			cart.setSpecDetailId(specId);
			Product pro=productService.getById(proId);
			cart.setSellerId(pro.getSellerId());
			cartService.save(cart);
			AjaxUtils.renderText(response, CommonConstants.SUCCESS);
		}catch(Exception e){
			e.printStackTrace();
			AjaxUtils.renderText(response, CommonConstants.FAIL);
		}
	}
	
	
	/**
	 * 产品数量+1
	 * @param request
	 * @param productId
	 * @param response
	 */
	@ResponseBody
	@RequestMapping("/addNum")
	public void addProductNum(HttpServletRequest request,
			Long cartId,HttpServletResponse response) {
		try{
			Cart cart = cartService.getCart(cartId);
			cart.setNum(cart.getNum()+1);
			cart.setFee((Integer)C.multiply(cart.getNum(),cart.getPrice()));
			cartService.update(cart);
			AjaxUtils.renderText(response, CommonConstants.SUCCESS);
		}catch(Exception e){
			logger.error("",e);
			AjaxUtils.renderText(response, CommonConstants.FAIL);
		}
	}
	
	
	/**
	 * 产品数量减一
	 * @param request
	 * @param productId
	 * @param response
	 */
	
	@ResponseBody
	@RequestMapping("/subNum")
	public void subProductNum(HttpServletRequest request, 
			Long cartId,HttpServletResponse response) {
		try{
			
			Cart cart = cartService.getCart(cartId);
			cart.setNum(cart.getNum()-1>=0?cart.getNum()-1:0);
			cart.setFee((Integer)C.multiply(cart.getNum(),cart.getPrice()));
			cartService.update(cart);
			AjaxUtils.renderText(response, CommonConstants.SUCCESS);
		}catch(Exception e){
			logger.error("",e);
			AjaxUtils.renderText(response, CommonConstants.FAIL);
		}
	}
	
	
	/**
	 * 购物车删除产品
	 * @param request
	 * @param productIds
	 * @param response
	 */
	
	@ResponseBody
	@RequestMapping("/delete")
	public void deleteProduct(
			@RequestParam List<Long>cartIds,
			HttpServletRequest request,
			HttpServletResponse response) {
		try{
			Map<String, Object>param=Maps.newHashMap();
			switch (cartIds.size()) {
			case 0:
				break;
			case 1:
				cartService.delete(cartIds.get(0));
				break;
			default:
				cartIds.remove(null);
				param.put("id in", cartIds);
				cartService.delete(param);
				break;
			}
			AjaxUtils.renderText(response, CommonConstants.SUCCESS);
		}catch(Exception e){
			logger.error("",e);
			AjaxUtils.renderText(response, CommonConstants.FAIL);
		}
	}
}
